package cn.easy.mortgage.web.app;

import cn.easy.base.SpringContext;
import cn.easy.base.service.AreaService;
import cn.easy.base.service.ConfigService;
import cn.easy.mortgage.bean.SelectBean;
import cn.easy.mortgage.service.CommonService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 通用方法控制器类
 *
 * @author chen
 * @date 2016/8/2
 */
@Controller
@RequestMapping("/app/common")
public class AppCommonController extends AppBaseController{
    @Autowired
    private AreaService areaService;
    @Autowired
    private CommonService commonService;

    @RequestMapping("/config")
    @ResponseBody
    List<SelectBean> config(String code, HttpServletRequest request) {
        List<SelectBean> selectBeanList = new ArrayList<>();
        Map<String, String> map = getConfigMap(code);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            selectBeanList.add(new SelectBean(entry.getValue(), entry.getKey()));
        }
        return selectBeanList;
    }

    @RequestMapping("/config/value")
    @ResponseBody
    String value(String configCode, String configValue) {
        Map<String, String> map = getConfigMap(configCode);
        return map.get(configValue);
    }

    @RequestMapping("/config/checkBoxValue")
    @ResponseBody
    String checkBoxValue(String configCode, String configValue) {
        return this.configService.getMultiBoxValue(configCode, configValue);
    }

    @RequestMapping("/upLoad")
    @ResponseBody
    String upLoad(String imgStr,String imgType) {
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            imgStr = imgStr.substring ("data:image/jpeg;base64,".length() -1 );
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                // 调整异常数据
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            // 生成图片
            String defaultRoot = SpringContext.getBean(ConfigService.class).getConfigValue("FILE_UPLOAD_DIR");
            String ext = "." + imgType.split("/")[1];
            String path = defaultRoot + "/weixin";
            File filePath = new File(path);
            if(!filePath.exists()){
                filePath.mkdir();
            }
            path = path + "/" + System.currentTimeMillis() + ext;
            OutputStream out = new FileOutputStream(path);
            out.write(bytes);
            out.flush();
            out.close();
            return path;
        } catch (Exception e) {

        }
        return   "";
    }

    /**
     * 预览图片
     * @param filePath
     * @param response
     * @throws IOException
     */
    @RequestMapping("/download")
    public void download(String filePath, HttpServletResponse response) throws IOException {
        File file = new File(filePath);
        if (file.exists()) {
            OutputStream os = response.getOutputStream();
            try {
                String fileName = URLEncoder.encode(filePath.substring(filePath.lastIndexOf("/")), "UTF-8");
                response.reset();
                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
                response.setContentType("application/octet-stream;charset=UTF-8");
                response.setHeader("Content-Length", String.valueOf(file.length()));
                os.write(FileUtils.readFileToByteArray(file));
                os.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (os != null) {
                    os.close();
                }
            }
        }
    }

    @RequestMapping({"/area/list"})
    @ResponseBody
    List<SelectBean> areaList(HttpServletRequest request, String parentCode, String codeType) {
        return commonService.getAreaList();
    }
}
